﻿using System;
using System.Linq;
using System.Xml.Linq;
using PivotServerTools;

namespace CollectionFactories.TeamCity
{
    class TeamCityProjectsCollectionFactory : TeamCityCollectionFactoryBase<TeamCityBuildTypesCollectionFactory>
    {
        public TeamCityProjectsCollectionFactory(TeamCityBuildTypesCollectionFactory inner) : base(inner)
        {
        }

        public override bool CanHandle(CollectionRequestContext context)
        {
            return string.IsNullOrEmpty(context.Query["type"]);
        }

        protected override Collection Handle(CollectionRequestContext context, string responseString)
        {
            XDocument document;

            try
            {
                document = XDocument.Parse(responseString);
            }
            catch (Exception e)
            {
                return ErrorCollection.FromException(e);
            }

            var projects = (from p in document.Descendants("project")
                            select new
                                       {
                                           Name = p.Attribute("name").Value,
                                           Id = p.Attribute("id").Value,
                                           RestUri = MakeRestUri(p.Attribute("href").Value)
                                       });

            var projectsWithDetails = from p in projects
                                      let details = XDocument.Parse(GetResponseString(string.Format("/app/rest/projects/id:{0}", p.Id))).Element("project")
                                      select new
                                                 {
                                                     p.Name,
                                                     p.Id,
                                                     Href = p.RestUri,
                                                     Url = MakeUserUri(details.Attribute("webUrl").Value),
                                                     BuildTypesUrl = MakeBuildTypesSourceUrl(context.Url, p.Id),
                                                     Description = details.Attribute("description").Value,
                                                     Archived = details.Attribute("archived").Value,
                                                 };

            var collection = new Collection { Name = "TeamCity projects" };

            foreach (var project in projectsWithDetails)
            {
                collection.AddItem(project.Name, project.BuildTypesUrl, project.Description, null,
                                   new Facet("Archived", FacetType.Text, project.Archived));
            }

            return collection;
        }

        private string MakeBuildTypesSourceUrl(string baseUrl, string projectId)
        {
            return Inner.CreateCollectionUri(new TeamCityAuthenticationData(this), baseUrl, projectId);
        }

        protected override string Resource(CollectionRequestContext context)
        {
            return "/app/rest/projects";
        }
    }
}